﻿
using System.Net;

namespace MyFurion.Unility.Generic
{
    /// <summary>
    /// 文件帮助类
    /// </summary>
    public static class FileHelper
    {
        /// <summary>
        /// 上传文件到Ftp
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="fileType">文件类型 如doc,png,pdf等</param>
        /// <param name="ftpUrl">ftp地址</param>
        /// <param name="ftpUser">ftp用户名</param>
        /// <param name="ftpPwd">ftp密码</param>
        /// <param name="filePath">文件保存地址</param>
        /// <returns></returns>
        public static bool FTPUploadFile(Stream stream, string fileType, string ftpUrl, string ftpUser, string ftpPwd, out string filePath)
        {
            try
            {
                string fileName = Guid.NewGuid().ToString() + "." + fileType;//文件名称
                string url = "";
                if (fileType == "doc")
                {
                    url = ftpUrl + @"/DocFiles/";
                }
                else if (fileType == "pdf")
                {
                    url = ftpUrl + @"/PdfFiles/";
                }
                else if (fileType == "xls" || fileType == "xlsx")
                {
                    url = ftpUrl + @"/ExcelFiles/";
                }
                else if (fileType == "jpg" || fileType == "png" || fileType == "gif" || fileType == "bmp")
                {
                    url = ftpUrl + @"/ImageFiles/";
                }
                else if (fileType == "zip" || fileType == "rar")
                {
                    url = ftpUrl + @"/ZipFiles/";
                }//.vob .ifo.(DVD格式).mpg .mpeg .dat .mp4 .3gp .mov .rm .ram .rmvb .wmv .asf.avi.asx
                else if (fileType == "mp4" || fileType == "mov" || fileType == "avi" || fileType == "rmvb")
                {
                    url = ftpUrl + @"/VideoFiles/";
                }
                else
                {
                    url = ftpUrl + @"/AttachFiles/";
                }
                CreateFTPDirrectory(url, ftpUser, ftpPwd);
                url = url + DateTime.Now.ToString("yyyyMMdd") + @"/";
                CreateFTPDirrectory(url, ftpUser, ftpPwd);
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url + fileName));//根据uri创建FtpWebRequest对象                                                                                    
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);// ftp用户名和密码
                // 默认为true，连接不会被关闭,在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // 指定数据传输类型
                reqFTP.UseBinary = true;
                Stream requestStream = reqFTP.GetRequestStream();
                byte[] fileBytes = new byte[stream.Length];
                stream.Read(fileBytes, 0, fileBytes.Length);
                stream.Seek(0, SeekOrigin.Begin);
                requestStream.Write(fileBytes, 0, fileBytes.Length);
                requestStream.Close();
                filePath = url + fileName;
                return true;
            }
            catch
            {
                filePath = "";
                return false;
            }
        }
        /// <summary>
        /// ftp下载文件
        /// </summary>
        /// <param name="ftpFullPath"></param>
        /// <param name="localFilePath">本地存储文件路径</param>
        /// <param name="ftpUser"></param>
        /// <param name="ftpPwd"></param>
        /// <returns></returns>
        public static bool FTPDownloadFile(string ftpFullPath,string localFilePath, string ftpUser, string ftpPwd)
        {
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFullPath));//根据uri创建FtpWebRequest对象                                                                                    
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);// ftp用户名和密码
                // 默认为true，连接不会被关闭,在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                Stream ftpStream = response.GetResponseStream();

                FileStream outputStream = new FileStream(localFilePath, FileMode.Create);
                int bufferSize = 2048;
                byte[] buffer = new byte[bufferSize];
                int readCount = ftpStream.Read(buffer, 0, bufferSize);
                while (readCount > 0)
                {
                    outputStream.Write(buffer, 0, readCount);
                    readCount = ftpStream.Read(buffer, 0, bufferSize);
                }
                ftpStream.Close();
                outputStream.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// ftp下载文件
        /// </summary>
        /// <param name="ftpFullPath"></param>
        /// <param name="ftpUser"></param>
        /// <param name="ftpPwd"></param>
        /// <returns></returns>
        public static Stream FTPDownloadFile(string ftpFullPath,string ftpUser, string ftpPwd)
        {
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpFullPath));//根据uri创建FtpWebRequest对象                                                                                    
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);// ftp用户名和密码
                // 默认为true，连接不会被关闭,在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
                reqFTP.UseBinary = true;
                FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
                return response.GetResponseStream();               
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 创建FTP文件夹路径
        /// </summary>
        /// <param name="ftpUrl"></param>
        /// <param name="ftpUser"></param>
        /// <param name="ftpPwd"></param>
        /// <returns></returns>
        public static bool CreateFTPDirrectory(string ftpUrl,string ftpUser,string ftpPwd)
        {
            bool isOk = true;
            if (!Directory.Exists(ftpUrl))
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpUrl));//根据uri创建FtpWebRequest对象 
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);// ftp用户名和密码
                reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
                try
                {
                    FtpWebResponse response = reqFTP.GetResponse() as FtpWebResponse;
                }
                catch
                {
                    isOk = false;
                }
            }
            return isOk;
        }
        /// <summary>
        /// 从ftp删除文件
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// <param name="ftpUser"></param>
        /// <param name="ftpPwd"></param>
        /// <returns></returns>
        public static bool FTPDeleteFile(string fileFullPath, string ftpUser, string ftpPwd)
        {
            try
            {
                FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(fileFullPath));//根据uri创建FtpWebRequest对象                                                                                    
                reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPwd);// ftp用户名和密码
                // 默认为true，连接不会被关闭,在一个命令之后被执行
                reqFTP.KeepAlive = false;
                // 指定执行什么命令
                reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                FtpWebResponse ftpWebResponse = (FtpWebResponse)reqFTP.GetResponse();
                long size = ftpWebResponse.ContentLength;
                Stream ftpResponseStream = ftpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(ftpResponseStream);
                streamReader.ReadToEnd();
                streamReader.Close();
                ftpResponseStream.Close();
                ftpWebResponse.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
    }
}
